﻿using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Identity.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore;
using ECommerce.AuthService.Models;

namespace ECommerce.AuthService.Data;

/// <summary>
/// 应用程序数据库上下文
/// 与AppUser保持类型一致，使用Guid作为主键
/// </summary>
public class AppDbContext : IdentityDbContext<
    AppUser,                   // 用户实体
    IdentityRole<Guid>,        // 角色实体（Guid主键）
    Guid>                      // 主键类型
{
    /// <summary>
    /// 刷新令牌数据集
    /// </summary>
    public DbSet<RefreshToken> RefreshTokens => Set<RefreshToken>();

    /// <summary>
    /// 构造函数
    /// </summary>
    public AppDbContext(DbContextOptions<AppDbContext> options) : base(options)
    {
    }

    /// <summary>
    /// 模型创建配置
    /// </summary>
    protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder); // 必须调用基类方法

        // 配置刷新令牌实体
        builder.Entity<RefreshToken>(entity =>
        {
            entity.HasOne<AppUser>()
                  .WithMany()
                  .HasForeignKey(rt => rt.UserId)
                  .OnDelete(DeleteBehavior.Cascade);

            entity.Property(rt => rt.Token)
                  .HasMaxLength(500)
                  .IsRequired();
        });

        // 自定义Identity表名，避免与其他服务冲突
        builder.Entity<AppUser>().ToTable("AuthUsers");
        builder.Entity<IdentityRole<Guid>>().ToTable("AuthRoles");
        builder.Entity<IdentityUserRole<Guid>>().ToTable("AuthUserRoles");
        builder.Entity<IdentityUserClaim<Guid>>().ToTable("AuthUserClaims");
        builder.Entity<IdentityUserLogin<Guid>>().ToTable("AuthUserLogins");
        builder.Entity<IdentityRoleClaim<Guid>>().ToTable("AuthRoleClaims");
        builder.Entity<IdentityUserToken<Guid>>().ToTable("AuthUserTokens");
    }
}
